<?php
/**
 * Created by PhpStorm.
 * User: hears
 * Date: 2017/11/17
 * Time: 11:48
 */

namespace App\Http\Proxy;


class TokenProxy {
	protected $http;
	public function __construct (\GuzzleHttp\Client $http) {
		$this->http = $http;
	}

	public function login ( $email,$password ) {
            if(auth()->attempt(['email'=>$email,'password'=>$password,'is_active'=>1])) {
	            return $this->proxy( 'password', [
		            'username' => $email,
		            'password' => $password,
		            'scope'    => ''
	            ] );
            }
            return response()->json([
            	'status'=>false,
	            'message'=>'Credentials not match'
            ],421);
    }
	public function proxy ($grantType,array $data = [] ) {
		$data = array_merge($data, [
			'client_id'     => '2',
			'client_secret' => "OIgMNNUs1wG94YelSYUvAyrevYyfQpRFbmd1ox5c",
			'grant_type'    => $grantType,
		] );
		$response = $this->http->post( 'http://localhost/oauth/token', [
			'form_params' => $data
		] );
		$token = json_decode((string) $response->getBody(), true );

		return response()->json( [
			'token'      => $token['access_token'],
			'expires_in' => $token['expires_in']
		] )->cookie( 'refreshToken', $token['refresh_token'],14400,null.null,false,true);
}
}